//
//  DWHTTPError.swift
//  DWSwift
//
//  Created by GDL on 2025/6/23.
//

import Foundation
import Moya
import Alamofire

public enum DWNetworkError: Error,CustomStringConvertible{
    // 1. 系统层错误（无网络、超时等）
    case systemError(code: Int, message: String)
    // 2. HTTP 状态码错误（非 2xx）
    case httpError(statusCode: Int, data: Data?)
    // 3. 数据解析错误（JSON/对象转换失败）
    case parsingError(description: String)
    // 4. 业务逻辑错误（服务器自定义错误码）
    case businessError(code: Int, message: String)
    // 5. 未知错误
    case unkownError(code: Int, message: String)
    
    public var description: String {
        switch self {
        case .systemError(let code, let message): return "code:\(code),原因:\(message)"
        case .httpError(let code, _): return "HTTP错误(\(code))"
        case .parsingError(let desc): return "解析失败:\(desc)"
        case .businessError(let code, let message): return "错误码:\(code),\(message)"
        case .unkownError(let code, let message):return "错误码:\(code),\(message)"
        }
    }
    
    //
    public static func mapMoyaError(_ error: MoyaError) -> DWNetworkError {
        switch error {
        case .statusCode(let response):
            // 提取 HTTP 状态码和原始数据
            return .httpError(statusCode: response.statusCode, data: response.data)
        case .underlying(let nsError as NSError, _):
            // 处理系统错误（如无网络、超时）
            // 尝试转换为 AFError
            if let afError = nsError.asAFError {
               return handleAFError(afError)
            }
            return handleSystemError(nsError)
        case .jsonMapping, .objectMapping, .stringMapping:
            // 统一解析错误
            return .parsingError(description: "服务数据解析异常")
        default:
            return .unkownError(code: -2, message: "MoyaError:未知错误")
        }
    }
    
    // 专用于处理AFError
    private static func handleAFError(_ error: AFError) -> DWNetworkError {
        switch error {
        case .sessionTaskFailed(let urlError):
           return handleSystemError(urlError as NSError) // 处理系统级错误
        default:
            return .unkownError(code: -1, message: "AFError:未知错误")
        }
    }
    
    private static func handleSystemError(_ error: NSError) -> DWNetworkError {
        switch error.code {
        case URLError.notConnectedToInternet.rawValue: // -1009
            return .systemError(code: error.code, message: "网络未连接")
        case URLError.timedOut.rawValue: // -1001
            return .systemError(code: error.code, message: "请求超时")
        case URLError.cannotConnectToHost.rawValue:
            return .systemError(code: error.code, message: "无法连接服务器")
        default:
            return .systemError(code: error.code, message: error.localizedDescription)
        }
    }
    
    static func parseBusinessError(from data: Data) -> DWNetworkError? {
        guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
              let code = json["code"] as? Int,
              let msg = json["msg"] as? String else {
            return nil
        }
        return .businessError(code: code, message: msg)
    }
}

// MARK:业务数据解析
extension DWNetworkError {
    static func pareBusinessError(from data:Data) ->DWNetworkError?{
        
       
        guard let json = try? JSONSerialization.jsonObject(with: data) as? [String:Any], let code=json["code"] as? Int, let msg=json["msg"] as? String else {
            // 解析失败
            // 不统一处理由业务层处理
            // 可以记录相关数据
            return .parsingError(description: "服务数据解析异常")
        }
        let response:DWBaseResponse = DWBaseResponse(code: code, data: "", msg: msg)

        if(response.isSuccess){ // 正常业务数据
            return nil
        }
        
        return .businessError(code: code, message: msg)
       
    }
}
